<template>
	<view class="coupon">
		<view>
			<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
				:down="downOption" :up="upOption">
				<block v-for="(item,index) in list" :key="index">
					<!-- 多选 -->
					<view class="coupon-item" @click="selectCoupon(item)">
						<view class="coupon-info" @click="myCouponDetail(item.id,item.coupontype_id)">
							<view class="" v-if="showRadio">
								<radio v-if="item.timeFlag == true" :checked="isChecked(item.id)"
									style="transform: scale(.8);flex-shrink: 0;margin-right: 8rpx;" color="#F12F63" />
								<radio v-else :disabled="true" :checked="isChecked(item.id)"
									style="transform: scale(.8);flex-shrink: 0;margin-right: 8rpx;" color="#F12F63" />
							</view>
							<view class="main-part">
								<view class="oil-item-name" v-if="item.coupontype_id*1 === 4">
									{{item.typename}} <text>(满{{item.full}}可用)</text>
								</view>
								<view class="oil-item-name" v-else>
									{{item.typename}} <text v-if="item.goods_name">（{{item.goods_name}}）</text>
								</view>
								<view class="oil-item-datatow" v-if="item.privilageno && item.coupontype_id*1 !== 3">
									核销码：{{item.privilageno}}</view>
								<view class="oil-item-expiration" v-if="item.coupontype_id*1 === 4">
									生效时间：{{expirationTime2(item.starttime)}}</view>
								<view class="oil-item-expiration">过期时间：{{expirationTime(item.expiretime)}}</view>
								<view class="oil-item-station" v-if="item.station_name">
									使用油站：<text class="oil-item-sn">{{item.station_name}}</text>
								</view>
							</view>
						</view>
						<view class="coupon-money">
							<view class="oil-item-data" @click="myCouponDetail(item.id)">
								<text>￥</text>
								{{item.price}}
							</view>
							<view class="oil-item-datas" v-if="item.coupontype_id*1 === 3 ||item.coupontype_id*1 === 4">
								{{item.status |status}}
							</view>
							<view class="oil-item-datas" v-else>
								<view class="status-btn" @click="writeOff(item.id,item.goods_name)" v-if="item.status==1">{{item.status |statuss}}</view>
								<view class="status-btn" v-else>{{item.status |status}}</view>
							</view>
						</view>
					</view>
				</block>
				<mescroll-empty v-if="list.length==0"></mescroll-empty>
			</mescroll-body>
		</view>
		<!-- 优惠券选择 确认 多选 -->
		<view class="coupon-confirm" v-if="showRadio">
			<view class="money">
				优惠券优惠￥
				<text>{{totalPrice}}</text>
			</view>
			<view class="confirm-btn" @click="checkedCoupon()">
				<text>确定</text>
			</view>
		</view>
		<!--  -->
		<view style="height: 120rpx;"></view>
	</view>
</template>

<script>
	import OilItem from '@/components/oil-item/oil-item.vue';
	import currentDate from '@/commom/js/currentDate.js';
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import api from '@/api/mine.js';
	import {
		timeFormat
	} from "@/utils/tool.js";
	export default {
		mixins: [MescrollMixin],
		components: {
			OilItem
		},
		data() {
			return {
				list: [],
				now: '', //当前时间
				downOption: {
					use: true,
				},
				timeFlag: true,
				upOption: {
					use: true,
					auto: true,
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 15, // 每页数据的数量
						time: 200 // 加载第一页数据服务器返回的时间; 防止用户翻页时,后台新增了数据从而导致下一页数据重复;
					},
					empty: {
						use: false, // 是否显示空布局
						icon: "https://www.mescroll.com/img/mescroll-empty.png", // 图标路径
						tip: '~ 暂无相关数据 ~', // 提示
						btnText: '去逛逛 >', // 按钮
						fixed: false, // 是否使用fixed定位,默认false; 配置fixed为true,以下的top和zIndex才生效 (transform会使fixed失效,最终会降级为absolute)
						top: "100rpx", // fixed定位的top值 (完整的单位值,如 "10%"; "100rpx")
						zIndex: 99 // fixed定位z-index值
					}
				},
				showRadio: false, // 默认radio不显示，当加油需要选择优惠券时显示radio
				coupons: [], // 优惠券多选
				total: '' //支付价格
			}
		},
		onLoad(option) {
			if (option.show) {
				this.total = option.total
				console.log(this.total);
				this.showRadio = true;
				this.now = currentDate.getDate();
			} else {
				this.showRadio = false;
			};

			// #ifdef MP-ALIPAY
			// 支付宝小程序关闭页面下拉(默认开启下拉)
			my.setCanPullDown({
				canPullDown: false
			});
			// #endif
		},
		filters: {
			status(val) {
				let strings = '';
				if (val == 1) {
					strings = '未使用';
				} else if (val == 2) {
					strings = '已使用';
				} else {
					strings = '已取消';
				};
				return strings;
			},
			statuss(val) {
				let strings = '';
				if (val == 1) {
					strings = '未核销';
				} else if (val == 2) {
					strings = '已核销';
				} else {
					strings = '已取消';
				};
				return strings;
			}
		},
		computed: {
			expirationTime() {
				return function(time) {
					let newTime = new Date().getTime(); // 获取当前时间戳
					if (newTime * 1 > time * 1 * 1000) {
						return "已过期";
					} else {
						return timeFormat(new Date(time * 1000), "yyyy-mm-dd hh:MM");
					};
				};
			},
			expirationTime2() {
				return function(time) {
					let newTime = new Date().getTime(); // 获取当前时间戳
					// if (newTime * 1 > time * 1 * 1000) {
					// return "已过期";
					// } else {
					return timeFormat(new Date(time * 1000), "yyyy-mm-dd hh:MM");
					// };
				};
			},
			totalPrice() {
				if (this.coupons.length > 0) {
					let total = 0;
					this.coupons.forEach(ele => {
						total += (ele.price * 1);
					});
					return total;
				} else {
					return 0;
				};
			},
			isChecked() { // 判断当前优惠券是否选中
				return function(id) {
					return this.coupons.some(item => {
						return item.id * 1 === id * 1;
					});
				};
			}
		},
		methods: {
			myCouponDetail(id,coupontype_id){
				if(coupontype_id == 4 && !this.showRadio){
					uni.navigateTo({
						url:"/pages_order/pages/myCoupon/index?id=" + id
					})
				}
			},
			writeOff(id,goods_name){
				let title = goods_name??'提示';
				uni.showModal({
						title: title,
						content: '是否确认核销?',
						success: function(res) {
							if (res.confirm) {
								 
								api.writeOff({id:id}).then(rs=>{
									uni.showToast({
										title: rs.msg,
										icon: 'none',
										duration: 1000
									});
									setTimeout(()=>{
										uni.reLaunch({
											url:"/pages/mine/coupon/coupon"
										})
									},1500)
								})
							
								uni.reload();
							} else if (res.cancel) {
								//console.log('取消');
								//TODO
							}
						}
				});
				
			},
			getCouponList() {
				api.getCouponList();
			},
			downCallback() {
				this.mescroll.resetUpScroll();
			},
			upCallback(page) {
				let data = {
					page: page.num
				};
				// 加油选择优惠券 
				if (this.showRadio) {
					data.coupontype_id = [3, 4]; // 3：加油券,4:满减券
					// data.coupontype_id = 3; // 3：加油券
					data.status = 1; // 1：待使用
				};
				//联网加载数据
				api.getCouponList(data).then(curPageData => {
					let list_data = curPageData.data.data.map(item => {
						return {
							id: item.id,
							typename: item.typename,
							privilageno: item.privilageno,
							status: item.status,
							price: item.price,
							expiretime: item.expiretime,
							goods_name: item.goods_name,
							coupontype_id: item.coupontype_id,
							createtime: item.createtime,
							starttime: item.starttime,
							full: item.full,
							station_name:item.station_name
						};
					});
					this.mescroll.endBySize(list_data.length, curPageData.data.total);
					//设置列表数据
					if (page.num == 1) this.list = [];
					this.list = this.list.concat(list_data);
					this.list.forEach((item, index) => { //js遍历数组
						if (item.coupontype_id * 1 === 4) {
							let obj1 = new Date(item.createtime) //有效期开始时间
							let obj = new Date(this.now) //当前时间
							if (obj.getTime() < item.starttime * 1000) {
								item.timeFlag = false
							} else {
								item.timeFlag = true
								// if (this.total === undefined) {
								// 	item.timeFlag = false
								// }
								if (this.total < item.full) {
									item.timeFlag = false
								}
							}
						} else {
							item.timeFlag = true
						}

					});
				}).catch(() => {
					this.mescroll.endErr();
				});
			},
			// 携带优惠券信息，返回加油页面
			checkedCoupon() {
				let _this = this;
				// 多选
				let price = 0;
				let ids = this.coupons.map(item => {
					price += (item.price * 1);
					return item.id;
				});
				let type = this.coupons.map(item => {
					return item.coupontype_id
				})
				let full = this.coupons.map(item => {
					if (item.full) {
						return item.full
					}
				})
				let totalData = {
					type: type,
					full: full,
					id: ids,
					price
				};
				uni.navigateBack({
					delta: 1,
					success() {
						uni.$emit('oil_coupon', totalData);
					}
				});
			},
			// 取消/选择 优惠券
			selectCoupon(item) {
				//console.log(OilItem,'选择优惠券')
				// 多选
				if (!this.showRadio) return;
				if (item.timeFlag == true) {
					if (this.isChecked(item.id)) {
						let ii = null;
						this.coupons.forEach((ele, index) => {
							if (ele.id * 1 === item.id * 1) {
								ii = index;
							};
						});
						this.coupons.splice(ii, 1);
					} else if (item.coupontype_id == 4) {


						let arr = []

						arr.push(item)

						this.coupons = arr
					} else {
						let res = this.coupons.find((ev) => {
							return ev.coupontype_id === 4;
						});

						if (res) {
							this.coupons = []
							this.coupons.push(item)
						} else {
							this.coupons.push(item)
						}
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.coupon {
		background-color: #F3F3F3;

		.coupon-item {
			min-height: 200rpx;
			display: flex;
			align-items: center;
			border-radius: 20rpx;
			background-color: #FFF;
			overflow: hidden;
			margin: 30rpx 30rpx 0;
			// box-shadow: rgba(149, 157, 165, 0.1) 0px 8px 24px;
			box-sizing: border-box;

			.coupon-money {
				min-height: 200rpx;
				background-color: #fff;
				position: relative;
				width: 30%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				border-radius: 0 16rpx 16rpx 0;
				border-left: 2rpx dashed #e5e5e5;
				box-sizing: border-box;

				.oil-item-data {
					color: #F12F63;
					font-size: 60rpx;
					font-weight: bold;

					text {
						font-size: 30rpx;
					}
				}

				.oil-item-datas {
					color: #555;
					font-size: 24rpx;
					.status-btn {
						color: #fff;
						text-align: center;
						font-size: 20rpx;
						padding: 10rpx 30rpx;
						border-radius: 200rpx;
						background-color: #F12F63;
					}
				}

				&::after {
					content: '';
					width: 20rpx;
					height: 20rpx;
					// border-radius: 50%;
					border-radius: 0 0 100rpx 100rpx;
					background-color: #f3f3f3;
					position: absolute;
					top: 0rpx;
					left: -10rpx;
				}

				&::before {
					content: '';
					width: 20rpx;
					height: 20rpx;
					border-radius: 100rpx 100rpx 0 0;
					background-color: #f3f3f3;
					position: absolute;
					bottom: 0rpx;
					left: -10rpx;
				}
			}

			.coupon-info {

				position: relative;
				flex: 1;
				height: 100%;
				background-color: #fff;
				display: flex;
				align-items: center;
				padding: 10rpx 30rpx;
				border-radius: 16rpx 0 0 16rpx;
				box-sizing: border-box;

				.main-part {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
				}

				.oil-item-name {
					font-size: 30rpx;
					font-weight: bold;
					padding-bottom: 12rpx;
				}

				.oil-item-datatow {
					font-size: 22rpx;
					color: #555;
					padding-bottom: 4rpx;
				}

				.oil-item-expiration {
					font-size: 22rpx;
					color: #555;
				}
				.oil-item-station{
					font-size: 22rpx;
					color: #555;
					.oil-item-sn{
						color: #F12F63;
					}
				}


				// 		&::after {
				// 			content: '';
				// 			width: 20rpx;
				// 			height: 20rpx;
				// 			border-radius: 50%;
				// 			background-color: #f3f3f3;
				// 			position: absolute;
				// 			top: -10rpx;
				// 			right: -10rpx;
				// 		}

				// 		&::before {
				// 			content: '';
				// 			width: 20rpx;
				// 			height: 20rpx;
				// 			border-radius: 50%;
				// 			background-color: #f3f3f3;
				// 			position: absolute;
				// 			bottom: -10rpx;
				// 			right: -10rpx;
				// 		}
			}

		}

		.coupon-confirm {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			padding: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			background-color: #fff;
			box-sizing: border-box;

			.money {
				font-size: 26rpx;
				font-weight: bold;

				text {
					font-size: 36rpx;
				}
			}

			.confirm-btn {
				width: 180rpx;
				height: 64rpx;
				line-height: 64rpx;
				background-color: #F12F63;
				font-size: 28rpx;
				color: #fff;
				text-align: center;
				border-radius: 8rpx;
			}
		}
	}
</style>
